<?php

declare(strict_types=1);
namespace App\Controller\AdminApi;
use App\Exception\XZXValidationException;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Service\SysExportLogService;
use App\Service\TradeOrderDetailService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Arr;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

/**
 * Class TradeOrderDetailController
 * @package App\Controller
 * @Controller(prefix="/admin/api/tradeOrderDetail")
 */
class TradeOrderDetailController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var TradeOrderDetailService
     */
    protected $TradeOrderDetailService;

    /**
     * @Inject()
     * @var SysExportLogService
     */
    protected $SysExportLogService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
        }
        $param['source'] = 2;
        return $this->TradeOrderDetailService->get($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(), [
                'page'               => 'required|integer|min:1',
                'limit'              => 'required|integer|min:1',
                'search.isSettle'    => 'sometimes|integer|max:2|min:0',
                'search.isRefund'    => 'sometimes|integer',
                'search.isDis'       => 'sometimes|integer',
                'search.isFrozen'    => 'sometimes|integer',
                'search.isThaw'      => 'sometimes|integer',
                'search.transStatus' => 'sometimes|integer|max:7|min:0',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'mchId');
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'tradeNo');
            CustomUtils::xzxAddSearch($param, $search, 'orderNo');
            CustomUtils::xzxAddSearch($param, $search, 'relNo');
            CustomUtils::xzxAddSearch($param, $search, 'mchUrl');
            CustomUtils::xzxAddSearch($param, $search, 'transStatus');
            CustomUtils::xzxAddSearch($param, $search, 'isSettle');
            CustomUtils::xzxAddSearch($param, $search, 'isRefund');
            CustomUtils::xzxAddSearch($param, $search, 'isDis');
            CustomUtils::xzxAddSearch($param, $search, 'isFrozen');
            CustomUtils::xzxAddSearch($param, $search, 'isThaw');
            CustomUtils::xzxAddSearch($param, $search, 'channelId');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
        }

        return $this->TradeOrderDetailService->list($param);
    }

    /**
     * 导出
     * @PostMapping(path = "exportExcel")
     * @Middleware(AdminJWTAuthMiddleware::class)
     * @param RequestInterface $request
     * @return array|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Throwable
     * @throws \TypeError
     */
    public function exportExcel(RequestInterface $request) {

        $type = 1;

        // 新增导出记录
        $ext = $this->request->getAttribute("ext");
        $result = $this->SysExportLogService->add(['type' => $type, 'createBy'=>$ext['createBy']]);

        $param = $request->all();
        // 直接把页数拖到很大
        $param['page'] = $request->post('page', 1);
        $param['limit'] = 10000000;

        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'mchId');
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'tradeNo');
            CustomUtils::xzxAddSearch($param, $search, 'orderNo');
            CustomUtils::xzxAddSearch($param, $search, 'relNo');
            CustomUtils::xzxAddSearch($param, $search, 'mchUrl');
            CustomUtils::xzxAddSearch($param, $search, 'transStatus');
            CustomUtils::xzxAddSearch($param, $search, 'isSettle');
            CustomUtils::xzxAddSearch($param, $search, 'isRefund');
            CustomUtils::xzxAddSearch($param, $search, 'isDis');
            CustomUtils::xzxAddSearch($param, $search, 'isFrozen');
            CustomUtils::xzxAddSearch($param, $search, 'isThaw');
            CustomUtils::xzxAddSearch($param, $search, 'channelId');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
        }

        $logId = $result['data'];
        $fileName = 'order-' . date('YmdHis') . rand(1000, 9999);
        $xlsCell = [
            ['filed' => 'mchNo',                'name'  => '商户号'],
            ['filed' => 'tradeNo',              'name'  => '交易流水'],
            ['filed' => 'orderNo',              'name'  => '商户订单号'],
            ['filed' => 'mchTransTime',         'name'  => '交易时间'],
            ['filed' => 'channelName',          'name'  => '通道名称'],
            ['filed' => 'floatMchTransAmount',  'name'  => '交易金额'],
            ['filed' => 'mchTransCurrency',     'name'  => '交易币种'],
            ['filed' => 'floatSettleAmount',    'name'  => '结算金额'],
            ['filed' => 'settleCurrency',       'name'  => '结算币种'],
            ['filed' => 'floatChannelTransAmount', 'name'  => '渠道交易金额'],
            ['filed' => 'channelTransCurrency', 'name'  => '渠道交易币种'],
            ['filed' => 'relNo',                'name'  => '渠道订单号'],
            ['filed' => 'floatServiceFee',      'name'  => '手续费'],
            ['filed' => 'floatPerFee',          'name'  => '单笔手续费'],
            ['filed' => 'settleCurrency',       'name'  => '手续费币种'],
            ['filed' => 'floatBondAmount',      'name'  => '保证金'],
            ['filed' => 'settleCurrency',       'name'  => '结算币种'],
            ['filed' => 'strTransStatus',       'name'  => '交易状态'],
            ['filed' => 'strIsDis',             'name'  => '拒付状态'],
            ['filed' => 'floatDisAmount',       'name'  => '拒付金额'],
            ['filed' => 'strIsRefund',          'name'  => '退款状态'],
            ['filed' => 'floatRefundAmount',    'name'  => '退款金额'],
            ['filed' => 'strIsFrozen',          'name'  => '冻结状态'],
            ['filed' => 'floatFrozenAmount',    'name'  => '冻结金额'],
            ['filed' => 'mchUrl',               'name'  => '网站'],
        ];

        $this->SysExportLogService->addToTask([
            'logId'     => $logId,
            'fileName'  => $fileName,
            'type'      => $type,
            'param'     => $param,
            'xlsCell'   => $xlsCell
        ]);

        return $result;
    }

    /**
     * 变更日志
     * @PostMapping(path = "log")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function log(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->TradeOrderDetailService->log($param);
    }

    /**
     * 商户拒付率
     * @PostMapping(path = "disRateList")
     * @Middleware(AdminJWTAuthMiddleware::class)
     *
     * @param RequestInterface $request
     *
     * @return array
     */
    public function disRateList (RequestInterface $request) {

        $validator = $this->validationFactory->make($request->all(), []);

        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $ext = $request->getAttribute('ext', []);

        $param = [
            'page' => $request->post('page'),
            'limit' => $request->post('limit'),
        ];
        $search = $request->post('search', []);

        if (!Arr::get($ext, 'isSuperRole')) {
            $param['mchIdList'] = Arr::get($ext, 'mchIdList', []);
        }

        CustomUtils::xzxAddSearch($param, $search, 'mchNo');
        CustomUtils::xzxAddSearch($param, $search, 'mchName');

        return $this->TradeOrderDetailService->disRateList($param);
    }

}
